<template>
	<div>
		<m-infinite
			v-model="loading"
			:isFinished="isFinished"
			@onload="getPexlesData"
		>
			<m-waterfall
				class="px-1 w-full"
				:data="pexelsList"
				nodeKey="id"
				:column="isMobileTerminal ? 2 : 5"
				:picturePreReading="false"
			>
				<template v-slot="{ item, width }">
					<item-vue @click="onToPins" :data="item" :width="width"></item-vue>
				</template>
			</m-waterfall>
		</m-infinite>

		<transition
			:css="false"
			@before-enter="beforeEnter"
			@enter="enter"
			@leave="leave"
		>
			<pins-vue v-if="isVisiblePins" :id="currentPins.id"></pins-vue>
		</transition>
	</div>
</template>

<script setup>
import { getPexlesList } from '@/api/pexels'
import { ref, watch } from 'vue'
import itemVue from './item.vue'
import { isMobileTerminal } from '@/utils/flexible.js'
import { useStore } from 'vuex'
import PinsVue from '@/views/pins/components/pins.vue'
import gsap from 'gsap'
import { useEventListener } from '@vueuse/core'

let query = {
	page: 1,
	size: 5,
}

const store = useStore()
const pexelsList = ref([])
const getPexlesData = async () => {
	if (isFinished.value) return

	if (pexelsList.value.length > 0) {
		query.page++
	}
	const res = await getPexlesList(query)
	pexelsList.value.push(...res.list)

	if (pexelsList.value.length === res.total) {
		isFinished.value = true
	}
	loading.value = false
}

const loading = ref(false)
const isFinished = ref(false)

const resetQuery = (newQuery) => {
	query = { ...query, ...newQuery }
	isFinished.value = false
	pexelsList.value = []
}
watch(
	() => store.getters.currentCategory,
	(currentCategory) => {
		resetQuery({
			page: 1,
			categoryId: currentCategory.id,
		})
	}
)

watch(
	() => store.getters.searchText,
	(val) => {
		resetQuery({
			page: 1,
			searchText: val,
		})
	}
)

// 监听浏览器后退事件
useEventListener(window, 'popstate', () => {
	isVisiblePins.value = false
})

const isVisiblePins = ref(false)
const currentPins = ref({})
const onToPins = (item) => {
	history.pushState(null, null, `/pins/${item.id}`)
	isVisiblePins.value = true
	currentPins.value = item
}

const beforeEnter = (el) => {
	gsap.set(el, {
		scaleX: 0,
		scaleY: 0,
		transformOrigin: '0 0',
		translateX: currentPins.value.translateX,
		translateY: currentPins.value.translateY,
		opacity: 0,
	})
}
const enter = (el, done) => {
	gsap.to(el, {
		duration: 0.3,
		scaleX: 1,
		scaleY: 1,
		opacity: 1,
		translateX: 0,
		translateY: 0,
		onComplete: done,
	})
}
const leave = (el, done) => {
	gsap.to(el, {
		duration: 0.3,
		scaleX: 0,
		scaleY: 0,
		opacity: 0,
		translateX: currentPins.value.translateX,
		translateY: currentPins.value.translateY,
		onComplete: done,
	})
}
</script>

<style scoped lang="scss"></style>
